import axios from 'axios';
import {
  Message,
  MessageBox
} from 'element-ui';
import store from '@/store'
import {
  getToken,
  setToken,
  getRefreshToken
} from '@/utils/auth';
import {
  refreshToken
} from '@/api/user';
import XEUtils from "xe-utils";
// 创建axios实例
let service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000 // 请求超时时间
})
// request拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers = {
      'Authorization': getToken(), //携带权限参数
      // 'X-Token': getToken(), //['X-Token'] is a custom headers key
    };
  }
  // config.baseURL = process.env.NODE_ENV === "production" ? "/api" : "/";

//   if (config.method == "get") {
//     config.headers["Content-Type"] = "application/x-www-form-urlencoded"
//     config.params = config.params || {};
//   } else {
//     config.headers["Content-Type"] = "application/json;charset=UTF-8"
//     config.data = config.data ? XEUtils.toJSONString(config.data) : XEUtils.toJSONString({});

//   }
  return config;
}, error => {
  Promise.reject(error)
});

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
     * code:200,接口正常返回;
     */
    const res = response.data;
    if (res.resultCode === 4012) { // Token到期，续租
      const pars = {
        "refreshToken": getRefreshToken()
      };
      refreshToken(pars).then(res => {
        if (res.resultCode === 200) {
          setToken(res.data.access_token);
          store.commit("SET_TOKEN", res.data.access_token);
          const backoff = new Promise(function (resolve) {
            setTimeout(function () {
              resolve();
            }, 500);
          });
          return backoff.then(function () {
            return axios(response.config);
          });
        }
      });
    } else if (res.resultCode !== 200) {
      if (res.resultCode === 4013 || res.resultCode === 4014) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('LogOut').then(() => {
            location.reload(); // 为了重新实例化vue-router对象 避免bug
          });
        });
      }
      Message({
        message: res.resultMessage,
        type: 'error',
        duration: 5 * 1000
      });
      return Promise.reject('error')
    } else {
      return response.data;
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
);

export default service;
